#include <QtCore>
#include <signal.h>

#include "RoModule.h"

#include "ScriptComponent.h"


void qApp_quit(int)
{
    qApp->quit();
}


int main(int argc, char * argv[])
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    QCoreApplication app(argc, argv);
    
    struct sigaction qApp_quit_sa;
    {
        qApp_quit_sa.sa_handler = qApp_quit;
        sigemptyset(&qApp_quit_sa.sa_mask);
        qApp_quit_sa.sa_flags = 0;
    }
    sigaction(SIGINT, &qApp_quit_sa, 0);
    sigaction(SIGHUP, &qApp_quit_sa, 0);
    sigaction(SIGTERM, &qApp_quit_sa, 0);

    QString runtimeDebugEnv = qgetenv("DEBUG").toLower();
    bool runtimeDebug = false;
    if ( not runtimeDebugEnv.isEmpty() )
    {
        if ( runtimeDebugEnv == "0" or
             runtimeDebugEnv == "false" or
             runtimeDebugEnv == "no" or
             runtimeDebugEnv == "off" )
        {
            runtimeDebug = false;
        }
        else
        {
            runtimeDebug = true;
        }
    }

    QPointer<RoModule> module = new RoModule(&app, runtimeDebug);
    QPointer<ScriptComponent> component = new ScriptComponent(module, app.arguments()[1]);

    QObject::connect(&app, SIGNAL( aboutToQuit() ),
                     module, SLOT( disconnectFromNetwork() ));
    QObject::connect(module, SIGNAL( error(QAbstractSocket::SocketError) ),
                     &app, SLOT( quit() ));
    QObject::connect(module, SIGNAL( connected() ),
                     component, SLOT( runScript() ));
    QObject::connect(component, SIGNAL( scriptFinished() ),
                     &app, SLOT( quit() ));
    
    module->connectToNetwork("localhost");

    return app.exec();
}
